package testjava;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

class CentralDirectoryEnd {
    // 0 4 End of central directory signature = 0x06054b50
    //  4 2 Number of this disk
    //  6 2 Disk where central directory starts
    //  8 2 Number of central directory records on this disk
    // 10 2 Total number of central directory records
    // 12 4 Size of central directory (bytes)
    // 16 4 Offset of start of central directory, relative to start of
    // archive
    // 20 2 Comment length (n)
    // 22 n Comment
    static final int SIG = 0x06054b50;
    static final int MIN_LEN = 22;
    short disk;
    short starts;
    short number;
    short total;
    int cdSize;
    int offset;
    short commentLength;

    public CentralDirectoryEnd(InputStream input) throws IOException {
        byte[] buffer = new byte[MIN_LEN];
        int len = input.read(buffer);
        if (len != buffer.length || SIG != Endian.getInt(buffer, 0)) {
            throw new IllegalArgumentException("unreadable CentralDirectoryEnd");
        }
        disk = Endian.getShort(buffer, 4);
        starts = Endian.getShort(buffer, 6);
        number = Endian.getShort(buffer, 8);
        total = Endian.getShort(buffer, 10);
        cdSize = Endian.getInt(buffer, 12);
        offset = Endian.getInt(buffer, 16);
        commentLength = Endian.getShort(buffer, 20);
    }

    public void writeTo(OutputStream out) throws IOException {
        out.write(Endian.getBytes(SIG));
        out.write(Endian.getBytes(disk));
        out.write(Endian.getBytes(starts));
        out.write(Endian.getBytes(number));
        out.write(Endian.getBytes(total));
        out.write(Endian.getBytes(cdSize));
        out.write(Endian.getBytes(offset));
        out.write(Endian.getBytes(commentLength));
    }

    @Override
    public String toString() {
        return "CentralDirectoryEnd [disk=" + disk + ", starts=" + starts + ", number=" + number + ", total=" + total + ", cdSize=" + cdSize
                + ", offset=" + offset + ", commentLength=" + commentLength + "]";
    }

}